<!doctype html><html lang=cn-zh><head><meta charset=UTF-8><meta name=viewport content="width=device-width,initial-scale=1"><meta http-equiv=X-UA-Compatible content="IE=edge"><style type=text/css>body{font-family:monospace}</style><title>Python|寻找最大最小的N个元素几种方法</title>
<meta name=description content="A blog maintained by Vimiix."><link rel=stylesheet href=/css/style.css><script>var _hmt=_hmt||[];(function(){var e,t=document.createElement("script");t.src="https://hm.baidu.com/hm.js?7c24231917964240bae97e813810620c",e=document.getElementsByTagName("script")[0],e.parentNode.insertBefore(t,e)})()</script></head><body><header>====================<br>== Hi, I'm Vimiix ==<br>====================<div style=float:right;color:gray;font-size:x-large>Get hands dirty.</div><br><p><nav><a href=https://www.vimiix.com/><b>首页</b></a>.
<a href=/posts/><b>文章列表</b></a>.
<a href=/projects/><b>开源项目</b></a>.
<a href=/tags/><b>标签</b></a>.
<a href=/friends/><b>友链</b></a>.
<a href=/about/><b>关于我</b></a>.
<a href=/index.xml><b>RSS</b></a>.</nav></p></header><main><article><h1>Python|寻找最大最小的N个元素几种方法</h1><b><time>2017.09.15 09:48</time></b>
<a href=/tags/python>Python</a>
<a href=/tags/sort>sort</a><div><p>实际的生产中，常常会需要处理一个序列，找出其中的 N 个最大或者最小的元素，这里提供几种思路，不同的情况，使用不同的搜索方式，可以更好提高我们代码的运行效率。</p><h6 id=这里先假设目标序列的元素总数为-s->“这里先假设目标序列的元素总数为 S ”</h6><h2 id=n-如果是-1>N 如果是 1</h2><p>如果只是简单地想找到最小或最大的元素，那么<code>min()</code>和<code>max()</code>是最合适的选择。</p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-Python data-lang=Python><span style=display:flex><span>	min([<span style=color:#ae81ff>1</span>,<span style=color:#ae81ff>2</span>,<span style=color:#ae81ff>3</span>]) <span style=color:#75715e>#1</span>
</span></span><span style=display:flex><span>	max([<span style=color:#ae81ff>1</span>,<span style=color:#ae81ff>2</span>,<span style=color:#ae81ff>3</span>]) <span style=color:#75715e>#3</span>
</span></span></code></pre></div><h2 id=n-如果想对-s-比较小>N 如果想对 S 比较小</h2><p>这种情况最高效的方式是使用函数<code>nlargest()</code>和<code>nsmallest()</code></p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-Python data-lang=Python><span style=display:flex><span>	<span style=color:#f92672>import</span> heapq
</span></span><span style=display:flex><span>	heapq<span style=color:#f92672>.</span>nlargest(N, nums) <span style=color:#75715e>#最大的N个元素组成的列表</span>
</span></span><span style=display:flex><span>	heapq<span style=color:#f92672>.</span>nsmallest(N, nums) <span style=color:#75715e>#最小的N个元素</span>
</span></span></code></pre></div><p>对于 N 较小的情况，还有一种高效的方式是下面这样：</p><p>heapq 的方式，这种方式首先会在底层将数据转为成列表，且元素会以堆得顺序排列。</p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-Python data-lang=Python><span style=display:flex><span>	nums <span style=color:#f92672>=</span> [<span style=color:#ae81ff>2</span>,<span style=color:#ae81ff>4</span>,<span style=color:#ae81ff>52</span>,<span style=color:#ae81ff>6</span>,<span style=color:#ae81ff>90</span>,<span style=color:#ae81ff>1</span>]
</span></span><span style=display:flex><span>	<span style=color:#f92672>import</span> heapq
</span></span><span style=display:flex><span>	heap <span style=color:#f92672>=</span> list(nums)
</span></span><span style=display:flex><span>	heapq<span style=color:#f92672>.</span>heapify(heap)
</span></span><span style=display:flex><span>	heap
</span></span><span style=display:flex><span>	[out]:[<span style=color:#ae81ff>1</span>, <span style=color:#ae81ff>4</span>, <span style=color:#ae81ff>2</span>, <span style=color:#ae81ff>6</span>, <span style=color:#ae81ff>90</span>, <span style=color:#ae81ff>52</span>]
</span></span></code></pre></div><p>堆最重要的特性就是 <code>heap[0]</code>永远是最小的那个元素。接下来的元素，可以依次通过<code>heapq.heappop()</code>方法找到，这个方法会将第一个元素，也就是最小的元素弹出，然后以第二小的元素代替。这种操作的复杂度为<code>O(logN)</code></p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-Python data-lang=Python><span style=display:flex><span>	heapq<span style=color:#f92672>.</span>heappop(heap)
</span></span><span style=display:flex><span>	[out]:<span style=color:#ae81ff>1</span>
</span></span><span style=display:flex><span>	heapq<span style=color:#f92672>.</span>heappop(heap)
</span></span><span style=display:flex><span>	[out]:<span style=color:#ae81ff>2</span>
</span></span></code></pre></div><h2 id=如果-n-和-s-相近>如果 N 和 S 相近</h2><p>这种情况下，通常更快的方法是先对集合排序，然后做切片操作。</p><div class=highlight><pre tabindex=0 style=color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4><code class=language-Python data-lang=Python><span style=display:flex><span>	sorted(nums)[:N]
</span></span><span style=display:flex><span>	<span style=color:#75715e>#或者</span>
</span></span><span style=display:flex><span>	sorted(nums)[<span style=color:#f92672>-</span>N:]
</span></span></code></pre></div><hr><blockquote><ul><li>版权声明：欢迎转载，请注明出处</li><li>发表日期：2017-09-15</li><li>博客地址：blog.vimiix.com</li></ul></blockquote></div></article></main><aside><div><div><h3>LATEST POSTS</h3></div><div><ul><li><a href=/posts/2025-10-16-kubernetes-apiserver-authorization-mechanism/>Kubernetes APIServer 鉴权机制</a></li><li><a href=/posts/2025-09-30-kubernetes-apiserver-authentication-mechanism/>Kubernetes APIServer 认证机制</a></li><li><a href=/posts/2024-12-16-deploy-kubernetes-by-kubeadm/>使用 kubeadm 搭建 kubernetes 集群</a></li><li><a href=/posts/2024-09-20-how-to-code-review/>如何做code review</a></li><li><a href=/posts/2024-08-12-weakref-in-python/>Python中的弱引用</a></li></ul></div></div></aside><footer><p>Social Links:
<a href=https://github.com/vimiix><b>Github</b></a>.
<a href=https://www.douban.com/people/vimiix/><b>Douban</b></a>.
<a href=mailto:i@vimiix.com><b>Email</b></a>.<br><hr>&copy; 2017-2025
Vimiix Yao; All rights reserved.
<a href=https://beian.miit.gov.cn/>京ICP备19015214号-1</a></p><script src=https://l2dwidget.js.org/lib/L2Dwidget.min.js></script><script>L2Dwidget.init({model:{jsonPath:"https://unpkg.com/live2d-widget-model-tororo@1.0.5/assets/tororo.model.json"}})</script></footer></body></html>